package com.dmcb.datasource;

import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.SqlSessionTemplate;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.jdbc.DataSourceBuilder;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;

import javax.sql.DataSource;

/**
 * Created by Administrator on 2018/7/25.
 */
@Configuration
@MapperScan(basePackages = "com.dmcb.trade.business.mappers", sqlSessionTemplateRef = "tradeSqlSessionTemplate")
public class TradeSourceConfig {


    @Bean(name = "tradeDataSource")
    @ConfigurationProperties(prefix="wechat.dataSource")
    public DataSource tradeDataSource() {
        return DataSourceBuilder.create().build();
    }

    /**
     * 配置session工厂
     */
    @Bean(name = "tradeSqlSessionFactory")
    public SqlSessionFactory tradeSqlSessionFactory(@Qualifier("tradeDataSource") DataSource dataSource) throws Exception {
        SqlSessionFactoryBean bean = new SqlSessionFactoryBean();
        bean.setDataSource(dataSource);
        bean.setMapperLocations(new PathMatchingResourcePatternResolver().getResources("classpath:mybatis/tradeMapper/*.xml"));
        return bean.getObject();
    }


    /**
     * 配置事务管理器
     */
    @Bean(name = "tradeTransactionManger")
    public DataSourceTransactionManager tradeTransactionManger(@Qualifier("tradeDataSource") DataSource dataSource) {
        return new DataSourceTransactionManager(dataSource);
    }

    /**
     * 模版
     */
    @Bean(name = "tradeSqlSessionTemplate")
    public SqlSessionTemplate tradeSqlSessionTemplate(@Qualifier("tradeSqlSessionFactory") SqlSessionFactory sqlSessionFactory) throws Exception {
        return new SqlSessionTemplate(sqlSessionFactory);
    }
}
